
import { addData } from './addData';
import { getDataById } from './getDataById';
import { updateDB } from './updateDB';
import { getDataByIndex } from './getDataByIndex';
import { getDataAll } from './getDataAll';
import { deleteDB } from './deleteDB';
import { getDataLikeCursor } from './getDataLikeCursor';
import { resultFomat, randomId , createDB , createTime} from './index';

export const storeName = 'meon';

/**
 * 添加或更新数据
 * @param {*} data
 * @returns
 */
export async function insertInfoDataItem(data) {
    const db = await createDB(storeName);
    const data_ = data.id ? await getDataById(db, storeName, data.id) : null;
    // 如果该主键对应的数据已存在，则做更新操作
    if (data_) {
      return updateDB(db, storeName, {...data,createTime:data.createTime?data.createTime:createTime()});
    }
    return addData(db, storeName, {...data,id:randomId(),createTime:createTime()});
  }
  

  /**
 * 获取全部数据
 * @param {*} data
 * @returns
 */
export async function getMeonDataAll() {
    const db = await createDB(storeName);
    const data_ = await getDataAll(db,storeName)
    return resultFomat(data_, 'rows');
}

/**
 * 便签根据id查询
 * @param {*} id 
 * @returns 
 */
export async function getMeonDataById(id) {
  const db = await createDB(storeName);
  const data_ = await getDataById(db, storeName, id);
  return resultFomat(data_, 'data', 'ok');
}

/**
 * 根据id删除
 * @param {*} id
 * @returns 
 */
export async function deleteMenoDataItemById(id) {
  const db = await createDB(storeName);
  const data_ = await deleteDB(db, storeName, id);
  return resultFomat(data_, 'data', 'ok');
}


/**
 * 模糊查询
 * @param { string } params 
 * @returns 
 */
export async function getMenoDataLike(params) {
  const key = 'name';
  const db = await createDB(storeName);
  const data_ = await getDataLikeCursor(db, storeName, {
    name: params[key]
  });
  return resultFomat(data_,'rows')
}


/**
 * 模糊查询
 * @param { string } params 
 * @returns 
 */
export async function getMenoDataTop4(params) {
  const db = await createDB(storeName);
  const data_ = await getDataAll(db, storeName);
  const top4Data = data_.splice(0, 4);
  return resultFomat(top4Data, 'rows');
}